package com.pdwl.cashoutpay.controller;

import com.pdwl.cashoutpay.entity.Trade;
import com.pdwl.cashoutpay.entity.res.BaseEntity;
import com.pdwl.cashoutpay.entity.res.TradeRes;
import com.pdwl.cashoutpay.service.OrderService;
import com.pdwl.cashoutpay.util.JsonUtil;
import com.pdwl.cashoutpay.util.LogUtils;
import com.pdwl.cashoutpay.util.Sign;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("query")
public class queryOrder {

    @Autowired
    private OrderService orderService;

    @RequestMapping("tradeQuery")
    public void query(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LogUtils.logInfo("下游开始查询订单");
        response.setHeader("Content-type", "textml;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        BaseEntity baseEntity = new BaseEntity();

        JSONObject map = JsonUtil.getJson(request);
        if (map.getString("sign").equals(Sign.getSign(map))) {
            String orderId = map.get("orderId") + "";
            String ourOrderId = map.get("ourOrderId") + "";

            Trade trade = new Trade();

            if (orderId.length() > 4) {
                trade = orderService.findByOrderId(orderId);
            }
            if (ourOrderId.length() > 4) {
                trade = orderService.findByOurOrderId(ourOrderId);
            }
//            
            if (trade != null) {
                TradeRes tradeRes = new TradeRes();
                tradeRes.setOrderid(trade.getOrderid());
                tradeRes.setOurorderid(trade.getOurorderid());
                tradeRes.setAmount(trade.getAmount());
                tradeRes.setNotifyurl(trade.getNotifyurl());
                tradeRes.setCriditno(trade.getCriditno());
                tradeRes.setBankphoneno(trade.getBankphoneno());
                tradeRes.setStatus(trade.getStatus());
                tradeRes.setMessage(trade.getMessage());

                baseEntity.setError_code("1");
                baseEntity.setError_message("查询成功！");
                baseEntity.setData(tradeRes);
            } else {
                baseEntity.setError_code("2");
                baseEntity.setError_message("查询失败！");
            }
        } else {
            LogUtils.logInfo("验签失败！");
            baseEntity.setError_code("20005");
            baseEntity.setError_message("验签失败，请重新验签！");
        }

        JSONObject json = JSONObject.fromObject(baseEntity);//将java对象转换为json对象
        String res = json.toString();
        response.getWriter().write(res);
    }


}
